<?php
/**
 *
 * @author Cao Thanh Hai
 * @version 
 */
require_once 'Zend/Loader/PluginLoader.php';
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * EventCommon Action Helper 
 * 
 * @uses actionHelper Zend_Controller_Action_Helper
 */
class Zend_Controller_Action_Helper_EventCommon extends Zend_Controller_Action_Helper_Abstract {
	/**
	 * @var Zend_Loader_PluginLoader
	 */
	public $pluginLoader;
	
	/**
	 * Constructor: initialize plugin loader
	 * 
	 * @return void
	 */
	public function __construct() {
		// TODO Auto-generated Constructor
		$this->pluginLoader = new Zend_Loader_PluginLoader ( );
	}
	
	/**
	 * Strategy pattern: call helper as broker method
	 */
	public function direct() {
		// TODO Auto-generated 'direct' method
	}
	
	
	private function getOtherHelper($helperName){
		return Zend_Controller_Action_HelperBroker::getStaticHelper($helperName);
	}
	
	
	public function buildHtmlEventLeftMenu($page='home', $uid, $cmdIdx=2, $termIndex=0, $isOwner=false){

		$termList = $this->getEventCategories();
		$banners = $this->getBanner($page);
        
        $ctrl = $this->_actionController;
        
        $searchCond = array();
        
        $req = $ctrl->getRequest();
        if($req->isPost()){
            $searchCond['keyword'] = $req->getPost('keyword', "");
            $searchCond['nwid'] = (int)$req->getPost('nwid', "");
            $searchCond['cid'] = (int)$req->getPost('cid', "");
            $searchCond['start_time'] = $req->getPost('start_time', "");
            $searchCond['end_time'] = $req->getPost('end_time', "");
        }
        else{
            $searchCond['keyword'] = $req->getQuery('keyword', "");
            $searchCond['nwid'] = $req->getQuery('nwid', 0);
            $searchCond['cid'] = $req->getQuery('cid', 0);
            $searchCond['start_time'] = $req->getQuery('start_time', "");
            $searchCond['end_time'] = $req->getQuery('end_time', "");
        }
        $searchCond['p'] = (int)$req->getPost('p', 0);
        
        if(!$searchCond['p']){
            $searchCond['p'] = (int)$req->getQuery('p', 0);
        }
		$data=$ctrl->view->partial('leftMenu.phtml', 
            array('cmdIdx'=>$cmdIdx, 'isOwner'=>$isOwner, 
                    'termIdx'=>$termIndex, 'termList'=>$termList, 
                    'uid'=>$uid, 'banners'=>$banners,
                    '$searchCond'=>$searchCond, 'action'=>$page));
		
		$layout = Zend_Layout::getMvcInstance();
		$layout->leftmenu = $data;
	}       
	
	public function htmlManageToolBlock($event){
		
		$ctrl = $this->_actionController;
		$assign_list = array();
		$user = $ctrl->getUser();
		
		$assign_list['event'] = $event;
		$assign_list['user'] = $user;
		$modelLoader = $this->getOtherHelper('modelLoader');
		$privacy = $this->getOtherHelper('privacy');
		$assign_list['isAdmin'] = $modelLoader->isEventAdmin($event->eid, $user->uid);
		$assign_list['isPublic'] = $privacy->isEventPublic($event->access);
		$assign_list['isPrivate'] = $privacy->isEventPrivate($event->access);
		$assign_list['isSecure'] = $privacy->isEventSecure($event->access);
		
		
		$memberStatus = $modelLoader->getMemberStatus($event->eid, $user->uid);
		$assign_list['memberStatus'] = $memberStatus;
		return $ctrl->view->partial('event/manage-tool.phtml', $assign_list);
	}
	
	public function getEventCategories(){
		$ctrl = $this->_actionController;
		$key = "event_event_terms";
		$categories = $ctrl->getCache($key);
		if($categories===false){
			$termModel = $ctrl->loadModel('Term');
			$categories = $termModel->getTermOfType('event');
			$ctrl->setCache($key, $categories);
		}
		return $categories;
	}
	
	public function buildHtmlEventLeftCol($eid){
		
		$event = $this->getOtherHelper('modelLoader')->getEventInfo($eid);
		
		$assign_list = array();
		$assign_list['htmlSameCategory'] = $this->buildHtmlSameCatBlock($eid);
		$assign_list['managerBlock'] = $this->htmlManageToolBlock($event);
		
		return $this->_actionController->view->partial('eventLeftCol.phtml', $assign_list);
	}
	
	public function buildHtmlSameCatBlock($eid){
		$ctrl = $this->_actionController;
		$cache_key = "html_same_cat_block_".$eid;
		
		$data = $ctrl->getCache($cache_key);
		if(!$data){
			$event = $this->getOtherHelper('modelLoader')->getEventInfo($eid);
			$categoryModel = $ctrl->loadModel('Term');
			$sameCatList = $categoryModel->getTermEventList($event->tid,0,6);
			
			$assign_list = array();
			$assign_list['pageInfo'] = $categoryModel->getPageInfo();
			$assign_list['event_list'] = $sameCatList;
			$assign_list['cid'] = $event->cid;
			
			$data = $ctrl->view->partial('event/samecat-block.phtml', $assign_list);
			$ctrl->setCache($cache_key, $data, EVENT_CACHE_PREFIX, 3600);
		}
		return $data;
		
	}
	
	public function buildHtmlHotBlock(){
		$ctrl = $this->_actionController;
		$cache_key = "html_hot_block";
		
		$data = $ctrl->getCache($cache_key);
		if(!$data){
			$eventModel = $ctrl->loadModel('Event');
			$hotList = $eventModel->getHotList(0,3);
			
			$assign_list = array();
			$assign_list['pageInfo'] = $eventModel->getPageInfo();
			$assign_list['event_list'] = $hotList;
			
			$data = $ctrl->view->partial('event/hot-block.phtml', $assign_list);
			$ctrl->setCache($cache_key, $data, EVENT_CACHE_PREFIX, 3600);
		}
		return $data;
		
	}
	
	public function getHtmlCommentList($event){

		$ctrl = $this->_actionController;
		$p = $ctrl->getRequest()->getQuery('page', 0);
		$user = $ctrl->getUser();
		$page_size = 10;
		
		$commentModel = $ctrl->loadModel('Comment');
		$commentModel->setRowPerPage($page_size);
		$commentList = $commentModel->getEventComment($event->vid, $event->comment_count, $p);
		
		$assign_list['comment'] = $commentList;
		$assign_list['count'] = $event->comment_count;
		$assign_list['page']=$p;
		$assign_list['page_count']=ceil($event->comment_count/$page_size);
		$assign_list['owner']=($user->uid==$event->uid);
		$assign_list['vid']=$event->vid;
		$assign_list['can_change'] = ($ctrl->isMod() || $ctrl->isAdmin());

		return $ctrl->view->partial('html_comment.php', $assign_list);
	}
	
	public function buildHtmlSearchBox($searchCond, $categoryList){

		$ctrl = $this->_actionController;
		
		$assign_list = array();
		//$assign_list['networkList'] = $networkList;
		$assign_list['categoryList'] = $categoryList;
		$assign_list['searchCond'] = $searchCond;
		return $ctrl->view->partial('search-box.phtml', $assign_list);
	}
    //va
    public function buildHtmlSearchBox_Home($searchCond, $categoryList){

        $ctrl = $this->_actionController;
        
        $assign_list = array();
        //$assign_list['networkList'] = $networkList;
        $assign_list['categoryList'] = $categoryList;
        $assign_list['searchCond'] = $searchCond;
        return $ctrl->view->partial('home/search-box-home.phtml', $assign_list);
    }
    //va
	
	public function buildPromotedBlock(){
		$cache_key = "html_play_related_block";
		$cache_time = 3600;
		$data = $this->_actionController->getCache($cache_key);
		if(!$data){
			
			//$eventModel = $this->_actionController->loadModel('Event');
			//$event_list = $eventModel->getClipList("noibat=1", "", 0, 12);
			//shuffle($event_list);
			//$assign_list = array();
			//$assign_list["event_list"]=$event_list;
			//$assign_list["url"]="category";
			
			//$content = $this->_actionController->view->partial("vlistInBox.phtml", array('url'=>"category", 'event_list'=>$event_list));
			$assign_list = array();
			
			$assign_list['boxName'] = "Event liên quan";
			$assign_list['boxNameStyle'] = "width:97%; cursor:pointer;";
			$assign_list['boxNameJs'] = "onClick=\"event_common.getRelate();\"";
			$assign_list['boxNameId'] = "t_related";
			$assign_list['boxContentId'] = "c_related";
			//$assign_list['boxContent'] = $content;
			$assign_list['boxContent'] = "";
			$assign_list['boxLoadingId'] = "ctl_loading_related";
			
			$data = $this->_actionController->view->partial('categoryBlock.phtml', $assign_list);
			$this->_actionController->setCache($cache_key, $data, EVENT_CACHE_PREFIX, $cache_time);
		}
		return $data;
	}
	
	public function cleanUserEventCache($eid, $uid, $oldStatus, $newStatus){
		$ctrl = $this->_actionController;
		$ctrl->deleteCache("member_status_".$eid."_".$uid);
		if($oldStatus == EVENT_USER_STATUS_MEMBER || $newStatus == EVENT_USER_STATUS_MEMBER){
			
			$ctrl->deleteCache("event_user_events_".$uid."_0_all");
			$ctrl->deleteCache("event_user_events_".$uid."_1_all");
			$ctrl->deleteCache("event_user_events_".$uid."_0_ongoing");
			$ctrl->deleteCache("event_user_events_".$uid."_1_ongoing");
			$ctrl->deleteCache("event_user_events_".$uid."_0_upcoming");
			$ctrl->deleteCache("event_user_events_".$uid."_1_upcoming");
			$ctrl->deleteCache("event_user_events_".$uid."_0_past");
			$ctrl->deleteCache("event_user_events_".$uid."_1_past");
			$ctrl->deleteCache("event_user_event_count_".$uid."_all");
			$ctrl->deleteCache("event_user_event_count_".$uid."_ongoing");
			$ctrl->deleteCache("event_user_event_count_".$uid."_upcoming");
			$ctrl->deleteCache("event_user_event_count_".$uid."_past");
			$ctrl->deleteCache("member_list_".$eid);
			
			$modelLoader = $this->getOtherHelper('modelLoader');
			$event = $modelLoader->getEventInfo($eid);
			if($event && $event->uid == $uid){
				$ctrl->deleteCache("event_user_own_events_".$uid."_0_all");
				$ctrl->deleteCache("event_user_own_events_".$uid."_1_all");
				$ctrl->deleteCache("event_user_own_events_".$uid."_0_ongoing");
				$ctrl->deleteCache("event_user_own_events_".$uid."_1_ongoing");
				$ctrl->deleteCache("event_user_own_events_".$uid."_0_upcoming");
				$ctrl->deleteCache("event_user_own_events_".$uid."_1_upcoming");
				$ctrl->deleteCache("event_user_own_events_".$uid."_0_past");
				$ctrl->deleteCache("event_user_own_events_".$uid."_1_past");
				$ctrl->deleteCache("event_user_own_event_count_".$uid."_all");
				$ctrl->deleteCache("event_user_own_event_count_".$uid."_ongoing");
				$ctrl->deleteCache("event_user_own_event_count_".$uid."_upcoming");
				$ctrl->deleteCache("event_user_own_event_count_".$uid."_past");
			}
		}
		
		if($oldStatus == EVENT_USER_STATUS_NOT || $newStatus == EVENT_USER_STATUS_NOT ||
			$oldStatus == EVENT_USER_STATUS_INVITED || $newStatus == EVENT_USER_STATUS_INVITED
		){
			
			$ctrl->deleteCache("event_my_invited_".$uid."_0");
			$ctrl->deleteCache("event_my_invited_".$uid."_1");
			$ctrl->deleteCache("event_my_invited_".$uid."_2");
			
			$ctrl->deleteCache("event_my_invited_count_".$uid);
			$ctrl->deleteCache("html_guest_block_".$eid);
			
		}
		
		if( $oldStatus == EVENT_USER_STATUS_MAYBE || $newStatus == EVENT_USER_STATUS_MAYBE 
		){
			
			$ctrl->deleteCache("event_my_invited_".$uid."_0_maybe");
			$ctrl->deleteCache("event_my_invited_".$uid."_1_maybe");
			$ctrl->deleteCache("event_my_invited_".$uid."_2_maybe");

			$ctrl->deleteCache("event_my_invited_count_".$uid."_maybe");
			$ctrl->deleteCache("html_guest_block_".$eid);
		}
		
		
	}
	
	public function buildSortBlock(){
		return "";
	}
	// $page; 'homepage' || 'category' || 'channel'
	public function buildPromotedChannelBlock($page='homepage'){
		$cache_time = 3600;
		$cache_key = "html_promoted_channel_block_".$page;
		$data = $this->_actionController->getCache($cache_key);
		if(!$data){
			$settings=$this->getSettings();
			
			$eventModel = AppGlobal::loadModel('Event');
			$channelModel = AppGlobal::loadModel('Channel');
			
			$tmp = $settings->$page;
			$promoted_list = $tmp["channel"];
			$channel = $channelModel->get($promoted_list[array_rand($promoted_list)]);
			$data['chanel_info'] = $channel;
			$data['event_list'] = $eventModel->getPromotedChanel($channel->chid);
			
			$data = $this->_actionController->view->partial("chanelPromoted.phtml", array("chanel" => $data));
			$this->_actionController->setCache($cache_key, $data, EVENT_CACHE_PREFIX, $cache_time);
		}
		return $data;
	}
	
	public function buildPromotedCategoryBlock($page='homepage'){
		$cache_time = 3600;
		$cache_key = "html_promoted_category_block_".$page;
		$data = $this->_actionController->getCache($cache_key);
		
		if(!$data){
			$settings=$this->getSettings();

			$termModel = AppGlobal::loadModel('Term');
			$eventModel = AppGlobal::loadModel('Event');
			$advs = array();
			switch($page){
				case 'homepage':
					$promoted_list=$settings->homepage["category"];
					$advs[] = $this->getBanner('home', 'right', 1);
					$advs[] = $this->getBanner('home', 'right', 2);
					break;
				case 'category':
					$promoted_list=$settings->category["category"];
					$advs[] = $this->getBanner('category', 'right', 0);
					$advs[] = $this->getBanner('category', 'right', 1);
					break;
				default:
					$page = 'default';
					$promoted_list=$settings->channel["category"];
					$advs[] = $this->getBanner('channel', 'right', 0);
					$advs[] = $this->getBanner('channel', 'right', 1);
					break;
			}
			
			$a=array_rand($promoted_list, 2);
			$tid[]= $termModel->get($promoted_list[$a[0]]);
			$tid[]= $termModel->get($promoted_list[$a[1]]);
			
			for ($i=0; $i<count($tid); $i++){
				$event_list["tid"]=$tid[$i]->tid;
				$event_list["term_name"]=$tid[$i]->name;
				$event_list["events"] = $eventModel->getClipByCategory($event_list["tid"], $termModel->getChildren($event_list["tid"]), null, "v.created DESC", 0, 12);
				$blocks[] = $this->_actionController->view->partial("categoryPromoted.phtml", array("event_list" => $event_list));
			}
			$data = $this->_actionController->view->partial($page."CategoryPromoted.phtml", array("blocks" => $blocks, 'advs'=>$advs));
			$this->_actionController->setCache($cache_key, $data, EVENT_CACHE_PREFIX, $cache_time);
		}
		return $data;
	}
	
	public function buildMainMenuBlock($index=0){
		$cache_time = 2*24*60*60;
		$cache_key = "html_main_menu_".($index>=0?$index:'null');
		$data = $this->_actionController->getCache($cache_key);
		if(!$data){
			$data=$this->_actionController->view->partial('mainMenu.phtml', array('active_menu'=>$index));
			$this->_actionController->setCache($cache_key, $data, EVENT_CACHE_PREFIX, $cache_time);
		}
		$layout = Zend_Layout::getMvcInstance();
		$layout->menu=$data;
	}
	
	public function buildButtonBlock(){
		$cache_time = 2*24*60*60;
		$cache_key = "html_button_block";
		$data = $this->_actionController->getCache($cache_key);
		if(!$data){
			$data = $this->_actionController->view->partial('buttons.phtml');
			$this->_actionController->setCache($cache_key, $data, EVENT_CACHE_PREFIX, $cache_time);
		}
		return $data;
	}
	
	public function buildFilterBlock($type='category'){
		$cache_time = 2*24*60*60;
		$cache_key = "html_filter_block_".$type;
		$data = $this->_actionController->getCache($cache_key);
		if(!$data){
			
			$data = $this->_actionController->view->partial('filterBox.phtml', array('type'=>$type));
			$this->_actionController->setCache($cache_key, $data, EVENT_CACHE_PREFIX, $cache_time);
		}
		return $data;
	}
	
	public function buildCategoryMenuBlock($catType='category', $catId=0){
		$cache_time = 2*24*60*60;
		$cache_key = "html_category_menu_block_".$catType."_".$catId;
		$data = $this->_actionController->getCache($cache_key);
		//$data = false;
		if(!$data){
			$termModel = $this->_actionController->loadModel('Term');
			$channelModel = $this->_actionController->loadModel('Channel');
			$assign_list = array();
			$assign_list['tree_term'] = $termModel->getAllCategory();
			$assign_list['channels'] = $channelModel->getAll(EVENT_CHANNEL_CHANNEL_TYPE);
			$assign_list['events'] = $channelModel->getAll(EVENT_CHANNEL_cid);
			$assign_list['schools'] = $channelModel->getAll(EVENT_CHANNEL_SCHOOL_TYPE);
			
			$assign_list['ids'] = array('catId'=>$catId, 'parents'=>array());
			if($catId > 0 && $catType=='category'){
				$assign_list['ids']['parents'] = $termModel->getParentIds($catId);
			}
			$assign_list['type'] = $catType;
			
			$data = $this->_actionController->view->partial('categoryMenuBox.phtml', $assign_list);
			
			
			$this->_actionController->setCache($cache_key, $data, EVENT_CACHE_PREFIX, $cache_time);
		}
		return $data;
	}
	
	public function buildChannelMenuBlock($channelId=0){
		$cache_time = 2*24*60*60;
		$cache_key = "html_channel_menu_block_".$channelId;
		$data = $this->_actionController->getCache($cache_key);
		if(!$data){
			$channelModel = $this->_actionController->loadModel('Channel');
			
			$assign_list['channels'] = $channelModel->getAll(EVENT_CHANNEL_CHANNEL_TYPE);
			$assign_list['events'] = $channelModel->getAll(EVENT_CHANNEL_cid);
			$assign_list['ids'] = array('channel'=>$channelId);
			$data = $this->_actionController->view->partial('categoryMenuBox.phtml', $assign_list);
			$this->_actionController->setCache($cache_key, $data, EVENT_CACHE_PREFIX, $cache_time);
		}
		return $data;
	}
	
	
	public function buildTagsBlock($cid= 0, $in=""){
		$cache_time = 2*24*60*60;
		$cache_key = "tags_cloud_".$cid."_".($in?1:0);
		$data = $this->_actionController->getCache($cache_key);
		if(!$data){
			$tagModel = $this->_actionController->loadModel('Tags');
			$data =  $tagModel->getTagCloud($cid, $in);
			$this->_actionController->setCache($cache_key, $data, EVENT_CACHE_PREFIX, $cache_time);
		}
		
		return $this->_actionController->view->partial('tags.phtml', array('tags_cloud'=>$data));
	}
	
	
	function getDefaultSettings()
	{
		$settings = (object) NULL;
		
		$settings->homepage=array();
		$settings->homepage["channel"]=array(41227);
		$settings->homepage["category"]=array(10330, 79184);
		
		$settings->category=array();
		$settings->category["channel"]=array(41227);
		$settings->category["category"]=array(10330, 79184);
		
		$settings->channel=array();
		$settings->channel["channel"]=array(41227);
		$settings->channel["category"]=array(10330, 79184);
		
		$settings->allowUpload=1;
		$settings->topUser=array(252239, 72869, 185568, 624871, 3016, 537856, 321315, 543634);
		return $settings;
	}
	
	public function getSettings()
	{
		$settings = $this->getVar('event_settings', null);
		if ($settings==NULL)
		{
			$settings = $this->getDefaultSettings();
		}
		return $settings;
	}
	
	public function getViewType()
	{
		if (isset($_COOKIE["vt"]))
		{
			$view_type=$_COOKIE["vt"];
		}
		else
		{
			$view_type=0;
		}
		if ($view_type==0)
		{
			$view_type="list";
		}
		else
		{
			$view_type="thumbnails";
		}
	    return $view_type;
	}
	
	public function getTreeTerm($checkPerm=false){
		
		$termDataModel = $this->_actionController->loadModel('Term');
		$treeTerm = $termDataModel->getAllCategory();
		$newTreeTerm = array();
		if(is_array($treeTerm) && count($treeTerm) > 0){
			
			foreach($treeTerm as $tree){
				$newTree = array();
				if(is_array($tree) && count($tree) > 0){
					foreach($tree as $term){
						
						if ($checkPerm && $term->roles!="" )
						{
							if ($this->_actionController->checkPerm($u,  $term->roles))
							{
								$newTree[]=$term;
							}
						}
						else
						{
							$newTree[]=$term;
						}
					}
				}
				if(!empty($newTree)){
					$newTreeTerm[] = $newTree;
				}
			
			}
			
		}
		
		return $newTreeTerm;
	}
	
	// @param type: 468x60, 728x90, 300x120, 300x250
	function getDefaultBannerCode($type){

		
		$defaultBanners = array();
		
		$defaultBanners['468'] = '<a href="#"><img width="468" height="60" border="0" src="/images/danhchoquangcao_468x60.gif"/></a>';
		$defaultBanners['728'] = '<a href="#"><img width="728" height="90" border="0" src="/images/danhchoquangcao_728x90.gif"/></a>';
		$defaultBanners['300'] = '<a href="#"><img width="300" height="120" border="0" src="/images/danhchoquangcao_300x120.gif"/></a>';
		$defaultBanners['300'] = '<a href="#"><img width="300" height="120" border="0" src="/images/danhchoquangcao_180x120.gif"/></a>';
		
		if($type <= count($defaultBanners))
			return $defaultBanners[$type];
		else return "";
	}
	
	function getBanner($page, $area="", $postion=0){
		$config = require APPLICATION_PATH . '/modules/event/config/adv_banners.php';
		
		$bannerTypes = $config['types'];
		$banners = $config['banners'];
		
		$ret = "";
		$postion = (int)$postion;
		if($page){
			if(isset($banners[$page])){
				if(!$area){
					$ret =  $banners[$page];
				}
				else if(isset($banners[$page][$area])){
					if(isset($banners[$page][$area][$postion])){
						$ret =  $banners[$page][$area][$postion];
					}
				}
			}
			if($ret == "" && isset($bannerTypes[$page]) && isset($bannerTypes[$page][$area])){
				$ret = $this->getDefaultBannerCode($bannerTypes[$page][$area]);
			}
		}
		
		return $ret;
	}
}



